﻿using MQTTnet;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MqttnetServerWin
{
    public partial class MqttnetServer : Form
    {
        #region 变量
        MQTTHelper _MQTTHelper = new MQTTHelper();
        #endregion 变量

        public MqttnetServer()
        {
            InitializeComponent();
        }
        private void MqttnetServer_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 启动按钮
        /// </summary>
        private void btn启动_Click(object sender, EventArgs e)
        {
            #region 配置校验
            if (string.IsNullOrEmpty(txt端口.Text.Trim()))
            {
                MessageBox.Show("运行中止，端口未指定！");
                return;
            }
            string ip = txtIP.Text.Trim();
            int port = Convert.ToInt32(txt端口.Text.Trim());
            bool isValidator = chk检查账户密码.Checked;

            string uName = txt用户名.Text.Trim();
            string uPwd = txt密码.Text.Trim();
            if (isValidator)  // 是否检测用户名和密码
            {
                if (string.IsNullOrEmpty(uName))
                {
                    MessageBox.Show("用户名不可为空");
                    return;
                }
                if (string.IsNullOrEmpty(uPwd))
                {
                    MessageBox.Show("密码不可为空");
                    return;
                }
            }
            #endregion 配置校验

            Action<ResultData_MQTT>? callback = ShowLog;

            bool withPersistentSessions = true;
            _MQTTHelper.CreateMQTTServerAndStart(ip, port, withPersistentSessions, callback);  // 开启服务
        }

        /// <summary>
        /// 停止按钮
        /// </summary>
        private void btn停止_Click(object sender, EventArgs e)
        {
            _MQTTHelper.StopMQTTServer();  // 停止服务
        }

        /// <summary>
        /// 处理逻辑-展示Log
        /// </summary>
        /// <param name="resultData_MQTT"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ShowLog(ResultData_MQTT resultData_MQTT)
        {
            this.Invoke(new Action(() =>
            {
                txt日志.Text += $"\r\n返回结果：{resultData_MQTT.ResultCode}，返回信息：{resultData_MQTT.ResultMsg}";
            }));
        }

        #region 其他
        private void txt端口_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }
        #endregion 其他
    }
}
